package global

import (
	"context"
	"fmt"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/qiniu/qmgo"

	"server/utils/timer"

	"github.com/songzhibin97/gkit/cache/local_cache"

	"golang.org/x/sync/singleflight"

	"go.uber.org/zap"

	"server/config"

	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/gorm"
)

var (
	A_DB        *gorm.DB
	A_DBList    map[string]*gorm.DB
	A_REDIS     redis.UniversalClient
	A_REDISList map[string]redis.UniversalClient
	A_MONGO     *qmgo.QmgoClient
	A_CONFIG    config.Server
	A_VP        *viper.Viper
	// A_LOG    *oplogging.Logger
	A_LOG                 *zap.Logger
	A_Timer               timer.Timer = timer.NewTimerTask()
	A_Concurrency_Control             = &singleflight.Group{}
	A_ROUTERS             gin.RoutesInfo
	A_ACTIVE_DBNAME       *string
	BlackCache            local_cache.Cache
	lock                  sync.RWMutex
)

// 全局上下文（基础上下文，无超时）
var A_CTX = context.Background()

// GetGlobalDBByDBName 通过名称获取db list中的db
func GetGlobalDBByDBName(dbname string) *gorm.DB {
	lock.RLock()
	defer lock.RUnlock()
	return A_DBList[dbname]
}

// MustGetGlobalDBByDBName 通过名称获取db 如果不存在则panic
func MustGetGlobalDBByDBName(dbname string) *gorm.DB {
	lock.RLock()
	defer lock.RUnlock()
	db, ok := A_DBList[dbname]
	if !ok || db == nil {
		panic("db no init")
	}
	return db
}

func GetRedis(name string) redis.UniversalClient {
	redis, ok := A_REDISList[name]
	if !ok || redis == nil {
		panic(fmt.Sprintf("redis `%s` no init", name))
	}
	return redis
}
